// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()

var faceDetect = function(url){
  const tencentcloud = require("tencentcloud-sdk-nodejs");

  const IaiClient = tencentcloud.iai.v20180301.Client;
  const models = tencentcloud.iai.v20180301.Models;

  const Credential = tencentcloud.common.Credential;
  const ClientProfile = tencentcloud.common.ClientProfile;
  const HttpProfile = tencentcloud.common.HttpProfile;

  let cred = new Credential("AKIDa3PWXQYgBH6lGdoMo9mIratAJNLEtuX1", "ZM0ZZedXO7Vs1iQ2d8biJ1JbpHdtaCQH");
  let httpProfile = new HttpProfile();
  httpProfile.endpoint = "iai.tencentcloudapi.com";
  let clientProfile = new ClientProfile();
  clientProfile.httpProfile = httpProfile;
  let client = new IaiClient(cred, "ap-guangzhou", clientProfile);

  let req = new models.DetectFaceRequest();

  let params = `{"MaxFaceNum":1,"MinFaceSize":1,"Url":"${url}","NeedQualityDetection":1}`
  req.from_json_string(params);

  return new Promise(function(resolve, reject){
    client.DetectFace(req, function (errMsg, response) {
      if (errMsg) {
        reject(errMsg)
      } else {
        reslove(response)
      }
    })
  })

}

// 云函数入口函数
exports.main = async (event, context) => {
  const data = event
  const fileList = [data.fileID]
  const result = await cloud.getTempFileURL({
    fileList,
  })
  const url = result.fileList[0].tempFileURL
  datas = await faceDetect(url)
  return datas
}